package com.ruoyi.bearing.service.Impl;

import cn.hutool.core.io.resource.BytesResource;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONPath;
import com.ruoyi.bearing.domain.BearingDiagnosisResult;
import com.ruoyi.bearing.domain.BearingModel;
import com.ruoyi.bearing.domain.BearingPredictResult;
import com.ruoyi.bearing.service.IBearingPredictionService;
import com.ruoyi.common.constant.FlaskDiagnosisConstants;
import com.ruoyi.common.constant.FlaskModelConstants;
import com.ruoyi.common.constant.FlaskPredictConstants;
import com.ruoyi.common.exception.flask.FlaskException;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.flask.HttpFlask;
import com.ruoyi.common.utils.http.HttpUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 在线预测
 */
@Service
public class BearingPredictionServiceImpl implements IBearingPredictionService {
    /**
     * 在线预测
     */
    public BearingPredictResult startBearingPrediction(MultipartFile file, BearingModel bearingModel) throws IOException, IllegalAccessException {
        BearingPredictResult bearingPredictResult = new BearingPredictResult();
        // 请求动态路径
        String res = HttpFlask.sendGetFlask(FlaskModelConstants.Model_CSV_URL);
        if (!"".equals(res)) {
            JSONObject jsonObject = JSONObject.parseObject(res);
            String dir = (String) jsonObject.get("data");
            String csvName = FileUploadUtils.upload(dir, file);
            String csvFileName = csvName.split("csv/")[1];
            bearingModel.setFileName(csvFileName);
            String postParam = HttpFlask.getKeyAndValueString(bearingModel);
            // 进行在线诊断
            // String diagnosisRes = HttpFlask.sendPostFlask(FlaskPredictConstants.Predict_URL, postParam);

            String diagnosisRes = HttpRequest.post(FlaskPredictConstants.Predict_URL)
                    .body(postParam)
                    .form("file", new BytesResource(file.getBytes(), file.getOriginalFilename()))
                    .execute().body();

            if (!"".equals(diagnosisRes)) {
                JSONObject predictJsonObject = JSONObject.parseObject(diagnosisRes).getJSONObject("data");
                // JSONArray json = (JSONArray) predictJsonObject.get("data");
                // JSONObject jRul = (JSONObject)json.get(0);
                // bearingPredictResult.setRul((String) jRul.get("rul"));
                // JSONObject j = (JSONObject) json.get(1);
                // JSONArray ja = (JSONArray) j.get("curve");
                // bearingPredictResult.setCurve(ja);
                JSONArray curves = new JSONArray();
                curves.add(predictJsonObject.getJSONArray("curve"));
                curves.add(predictJsonObject.getJSONArray("rul_values"));

                bearingPredictResult.setCurve(curves);
                // bearingPredictResult.setRuls(predictJsonObject.getJSONArray("rul_values"));

                return bearingPredictResult;
            }
        }
        return null;
    }

    /**
     * 下载在线预测结果
     */
    public void download(HttpServletResponse response, BearingModel bearingModel) {
        try {
            String res = HttpFlask.sendGetFlask(FlaskPredictConstants.PREDICTION_RESULT_URL);
            if (!"".equals(res)) {
                JSONObject jsonObject = JSONObject.parseObject(res);
                String dir = (String) jsonObject.get("data");
                ServletOutputStream outputStream = response.getOutputStream();
                BufferedReader reader = new BufferedReader(new FileReader(dir + "//result.csv"));
                String line;
                while ((line = reader.readLine()) != null) {
                    outputStream.write(line.getBytes(StandardCharsets.UTF_8));
                    outputStream.write('\n');
                }
                reader.close();
                outputStream.close();
            } else {
                throw new FlaskException();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
